import React, { useState } from 'react';
import { Card, Avatar, Typography, Input, Button, message, Upload } from 'antd';
import { UploadOutlined, UserOutlined } from '@ant-design/icons';
import { useUserStore } from '../store/user';
import { updateAvatar, updateNickname } from '../api/user';

const { Title } = Typography;

const Profile: React.FC = () => {
  const { userId, userName, nickName, avatarUrl, setUserInfo, token, isAdmin } = useUserStore();
  const [nickname, setNickname] = useState(nickName || '');
  const [avatar, setAvatar] = useState(avatarUrl || '');
  const [editing, setEditing] = useState(false);
  const [avatarFile, setAvatarFile] = useState<File | null>(null);
  const [uploading, setUploading] = useState(false);
  const [saving, setSaving] = useState(false);

  // 头像上传前预览并自动上传
  const beforeUpload = async (file: File) => {
    setAvatarFile(file);
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => setAvatar(reader.result as string);
    // 自动上传到后端
    setUploading(true);
    try {
      const res = await updateAvatar(file, userId);
      if (res.data && res.data.success) {
        message.success('头像已更新');
        // 这里建议后端返回新头像url，前端可用 setAvatar(res.data.data.avatarUrl)
      } else {
        message.error(res.data.message || '头像上传失败');
      }
    } catch (e) {
      message.error('头像上传失败');
    }
    setUploading(false);
    return false; // 阻止自动上传
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const res = await updateNickname(nickname);
      if (res.data && res.data.success) {
        setUserInfo(userId, token, userName, isAdmin, nickname, avatar);
        message.success('个人信息已更新');
        setEditing(false);
      } else {
        message.error(res.data.message || '昵称修改失败');
      }
    } catch (e) {
      message.error('昵称修改失败');
    }
    setSaving(false);
  };

  return (
    <div style={{ maxWidth: 400, margin: '40px auto' }}>
      <Card>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <Avatar src={avatar || undefined} size={80} icon={!avatar && <UserOutlined />} />
          <div style={{ marginTop: 12 }}>
            {editing && (
              <Upload
                showUploadList={false}
                beforeUpload={beforeUpload}
                accept="image/*"
                disabled={uploading}
              >
                <Button icon={<UploadOutlined />} loading={uploading}>更换头像</Button>
              </Upload>
            )}
          </div>
          <Title level={4} style={{ marginTop: 16 }}>账号：{userName}</Title>
          <div style={{ marginTop: 16, width: '100%' }}>
            <span>昵称：</span>
            {editing ? (
              <>
                <Input value={nickname} onChange={e => setNickname(e.target.value)} style={{ width: 180 }} />
                <Button type="primary" size="small" onClick={handleSave} style={{ marginLeft: 8 }} loading={saving}>保存</Button>
                <Button size="small" onClick={() => { setNickname(nickName); setAvatar(avatarUrl); setEditing(false); }} style={{ marginLeft: 4 }}>取消</Button>
              </>
            ) : (
              <>
                <span style={{ fontWeight: 'bold' }}>{nickname}</span>
                <Button type="link" size="small" onClick={() => setEditing(true)} style={{ marginLeft: 8 }}>修改</Button>
              </>
            )}
          </div>
        </div>
      </Card>
    </div>
  );
};

export default Profile; 